<template>
  <div class="chat">
    <NavHeader title="萤星对话" />
    <div class="chat-contanier">
      <div class="contanier-left">
        <LeftSider
          :id="id"
          title="对话"
          :list="chatlist"
          @transmit="getMessage"
          @del="del"
          @clear="clear"
        />
      </div>
      <div class="contanier-right">
        <div ref="chatScroll" class="chat-content" @scroll="handleScroll">
          <span v-for="(message, index) in messagelist" :key="index">
            <div class="chat-list">
              <div v-if="message.role == 'my'" class="avatar">
                <img
                  src="@/assets/imgs/avatar.jpg"
                  width="30px"
                  height="30px"
                />
              </div>
              <v-md-preview
                v-if="message.role == 'my'"
                class="content"
                :text="message.text"
              />

              <div v-if="message.role == 'gpt'" class="avatar">
                <img
                  src=""
                  width="30px"
                  height="30px"
                />
              </div>
              <v-md-preview
                v-if="message.role == 'gpt'"
                class="content answer"
                :text="message.text"
              />
            </div>
          </span>
        </div>
        <div class="chat-input">
          <div
            v-show="showtToBottomBtn"
            class="to-top"
            @click="scrollToBottom('chatScroll', 'smooth')"
          >
            <i class="el-icon-bottom"></i>
          </div>
          <div class="lb-chat-textarea">
            <div class="lb-chat-textarea-container">
              <el-input
                v-model="text"
                maxlength="500"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }"
                placeholder="请输入内容回车键提交对话"
                @keyup.enter.native="checkTokens"
              >
              </el-input>
            </div>
            <div class="lb-chat-textarea-btn">
              <i class="el-icon-s-promotion" @click="checkTokens"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavHeader from "@/components/NavHeader";
import LeftSider from "@/components/LeftSider";
import { fetchService } from "@/utils/common";
import { getChatHis, updateChatHis, delChatHis } from "@/api/translate";
import { getUserToken } from "@/api/api";
import { fetchData } from "@/utils";

export default {
  name: "Chat",
  components: {
    NavHeader,
    LeftSider,
  },
  data() {
    return {
      messagelist: [],
      text: "",
      pagenum: 1,
      pages: 0,
      chatlist: [],
      cacheFilter: { type: "3" },
      id: 0,
      showtToBottomBtn: false,
    };
  },
  mounted() {
    this.getChatHisList();
  },

  methods: {
    handleScroll(e) {
      let scroll =
        e.target.scrollHeight - e.target.clientHeight - e.target.scrollTop;
      if (scroll > 100) {
        this.showtToBottomBtn = true;
      } else {
        this.showtToBottomBtn = false;
      }
    },
    checkTokens() {
      fetchData(getUserToken, 1)
      .then((res) => {
        if(res) {
          this.chat()
        } else {
          this.$message.warning("您的token不足，请充值!");
        }
      });
    },
    async chat() {
      this.messagelist.push({ text: this.text, role: "my" });

      let textSay = this.text;

      if (this.text.trim() == "") {
        this.$message.warning("请输入内容！");
        return;
      }
      this.text = "";
      const res = await fetchService("chat/chat", { text: textSay });

      let a = true;
      const reader = res
        // eslint-disable-next-line no-undef
        .pipeThrough(new TextDecoderStream())
        .getReader();
      let i = this.messagelist.length;
      this.messagelist.push({ text: "", role: "gpt" });
      while (a) {
        var { value, done } = await reader.read();
        if (done) break;
        this.messagelist[i].text += value?.replace("undefined", "");
        this.scrollToBottom("chatScroll");
      }
      //每次聊天完之后更新数据库历史记录
      this.updateHis();
    },
    updateHis() {
      fetchData(
        updateChatHis,
        {
          ...this.cacheFilter,
          fromtext: this.messagelist[0].text,
          backtext: JSON.stringify(this.messagelist),
          id: this.id,
        },
        false
      ).then(() => {
        this.getChatHisList(1);
      });
    },
    getChatHisList(type) {
      fetchData(
        getChatHis,
        {
          ...this.cacheFilter,
          pagesize: 20,
          pagenum: this.pagenum,
        },
        false
      ).then((res) => {
        this.chatlist = res?.list || [];
        this.pages = res.pages;3
        if(type == 1) {
          this.id = this.chatlist[0].id
        }
      });
    },
    getMessage(data) {
      data.syncstatus = "01";
      this.messagelist = data.backtext ? JSON.parse(data.backtext) : {}; //data即为子组件发送的数据
      this.id = data.id;
      this.scrollToBottom("chatScroll");
    },
    scrollToBottom(targetElement, behavior = "auto") {
      this.$nextTick(() => {
        // 等待DOM更新完成后才能正确地获取到元素引用
        const target = this.$refs[targetElement];
        target.scrollTo({ top: target.scrollHeight, behavior: behavior });
      });
    },
    del(data) {
      fetchData(delChatHis, { id: data.id }, false).then(() => {
        this.$message.success("删除成功!");
        this.pagenum = 1;
        this.getChatHisList();
        this.clear();
      });
    },
    clear() {
      if (this.id == 0) {
        this.$message.warning("当前已是新对话!");
      } else {
        this.id = 0;
        this.messagelist = [];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.chat {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .chat-contanier {
    flex: 1;
    display: flex;
    overflow: hidden;
    .contanier-left {
      height: 100%;
    }
    .contanier-right {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow-y: hidden;
      .chat-content {
        flex: 1;
        min-width: 800px;
        border-bottom: 1px solid #e5e5e5;
        background: #f7f7f8;
        padding-bottom: 30px;
        overflow-y: auto;
        box-sizing: border-box;
        .chat-list {
          width: 700px;
          display: flex;
          align-items: flex-start;
          padding: 30px 0;
          margin: 0 auto;
          box-sizing: border-box;
          .avatar {
            width: 30px;
            height: 30px;
            border-radius: 5px;
            border: 1px solid #e5e5e5;
            margin-right: 26px;
            img {
              width: 100%;
              height: 100%;
              border-radius: 5px;
            }
          }
          .content {
            font-size: 16px;
            line-height: 30px;
            word-break: break-all;
            max-width: 600px;
            &.answer {
              background: #fff;
              padding: 20px;
              box-sizing: border-box;
              border-radius: 8px;
              box-shadow: 2px 0 12px 1px #0000000f;
            }
            /deep/ ol {
              padding-left: 2em;
            }
            /deep/ li {
              list-style-type: decimal;
              list-style-position: outside;
              margin-left: 5px;
            }
          }
          /deep/ .github-markdown-body {
            padding: 0;
            p {
              margin-bottom: 0px;
            }
          }
        }
      }
      .chat-input {
        padding: 40px 0;
        position: relative;
        .to-top {
          position: absolute;
          top: -20px;
          right: 100px;
          width: 30px;
          height: 30px;
          background: white;
          border-radius: 50%;
          border: 1px solid #e5e5e5;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          color: #999;
          cursor: pointer;
        }
        .lb-chat-textarea {
          width: 700px;
          margin: 0 auto;
          background: white;
          display: flex;
          align-items: flex-end;
          border-radius: 12px;
          border: 1px solid #e5e5e5;
          .lb-chat-textarea-container {
            flex: 1;
            margin-right: 1%;
            padding: 10px 15px;
            /deep/ .el-textarea__inner {
              outline: none;
              border: none;
              padding: 0;
              line-height: 24px;
              resize: none;
              height: 24px;
              width: 100%;
            }
          }
          .lb-chat-textarea-btn {
            margin-bottom: 10px;
            margin-right: 10px;
            .el-icon-s-promotion {
              color: #1296db;
              font-size: 20px;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}
</style>
